package com.ericsson.entironment.manager;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ericsson.common.db.DatabaseMng;
import com.ericsson.common.exception.SmafException;
import com.ericsson.entironment.bean.HouseBean;
import com.ericsson.entironment.util.ResultCode;

public class HouseManager
{
	public static ResultCode saveNew(String name,String address)
	{
		ResultCode code=new ResultCode();
		//检查是否已经存在
		HouseBean house=new HouseBean();
		house.loadByName(name);
		if (house.getHsid()==null)
		{//大棚没有重名可以加入
			
			house.setHsaddreess(address);
			house.setHsname(name);
			try
			{
				house.save();
			}
			catch (SmafException e)
			{
				code.setResult("failure");
				code.setMessage("系统错误，无法完成大棚的新增");
				return code;
			}
			code.setResult("success");
		}
		else
		{
			code.setResult("failure");
			code.setMessage("大棚名称重复，请重新输入");
		}
		return code;
	}
	private static Log log=LogFactory.getLog(HouseManager.class);
	public List getHouseList()
	{
		Connection conn = null;
		Statement stmt = null;
		ResultSet rst = null;
		String sql = "";
		List terminal=null;
		List list=new ArrayList();
		HouseBean house=new HouseBean();
		String options="";
		try
		{
			conn = DatabaseMng.getInstance().getConnection();
			stmt = conn.createStatement();
	
			sql="select * from ema_greenhouse";
			
			rst=stmt.executeQuery(sql);
			while (rst.next())
			{	
				
				house.loadById(rst.getString("hsid"));
				options="";
				if (house.getHsid()!=null)
				{
					terminal=new ArrayList();
					terminal.add(house.getHsid());
					terminal.add(house.getHsname());
					terminal.add(house.getHsaddreess());
					terminal.add(house.getTerminal());
					if(house.hasAlert())
					{
						options="<img src='./image/alert.gif' width=16 height=16 title='系统告警'>&nbsp;&nbsp;";
					}
					options+="<a href='javascript:houseDetail(\""+house.getHsid()+"\",\""+house.getHsname()+"\")'><img src='./image/detail.gif' width=16 height=16 title='查看详情'></a>"
							+"&nbsp;&nbsp;<a href='javascript:deleteHouse(\""+house.getHsid()+"\",\""+house.getHsname()+"\")'><img src='./image/delete.gif' width=16 height=16 title='删除记录'></a>";
					
					terminal.add(options);
					list.add(terminal);
					
				}
			}
			

		}
		catch (Exception e)
		{
			log.error("载入大棚数据失败，执行数据库操作失败 sql["+sql+"]",e);
			
		}
		finally
		{
			try
			{
				if (rst != null)
					rst.close();
				if (stmt != null)
					stmt.close();
				if (conn != null)
					conn.close();
			}
			catch (Exception e)
			{

			}

		}
		return list;
	}


	public List del(String id)
	{
		HouseBean house=new HouseBean();
		house.loadById(id);
		house.delete();
		return getHouseList();
	}
}
